package com.gxa.luckin.order.task;

import com.gxa.luckin.order.pojo.OrderStatus;
import com.gxa.luckin.order.repository.OrderStatusRepository;
import com.gxa.luckin.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author: XHZ
 * @date: 10:00 2021/7/19
 */
@Slf4j
public class OrderTask {

    @Resource
    private OrderStatusRepository orderStatusRepository;

    @Resource
    private OrderService orderService;

    //分布式锁解决集群部署问题或者使用分布式job
    //每隔一分钟扫描一次
    @Scheduled(cron = "0 0/1 * * * ?")
    public void inventoryLockTask() {

        log.info("定时器启动,扫描超时未支付订单中.......................");

        //1.查询当前所有超时未支付订单
        List<OrderStatus> orderStatusList = orderStatusRepository.queryOrderStatusMorePayTime(new Date());

        //2.遍历超时未支付订单
        orderStatusList.forEach(orderStatus -> {

            //3.修改订单状态为取消并且加回商品库存，注意分布式事务问题
            orderService.cancelOrder(orderStatus.getOrderId());

        });
    }
}
